package com.example.myapplicationktkt2.audiovideo

import android.media.MediaPlayer
import android.os.Bundle
import android.widget.Button
import android.widget.SeekBar
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import com.example.myapplicationktkt2.R
import java.io.IOException

class AudioPlayerDemoActivity : AppCompatActivity() {

    private var mediaPlayer: MediaPlayer? = null
    private lateinit var playButton: Button
    private lateinit var pauseButton: Button
    private lateinit var stopButton: Button
    private lateinit var seekBar: SeekBar
    private lateinit var statusText: TextView
    private lateinit var progressText: TextView
    
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_audio_player_demo)
        
        initViews()
        initMediaPlayer()
        setupListeners()
    }
    
    private fun initViews() {
        playButton = findViewById(R.id.btn_play)
        pauseButton = findViewById(R.id.btn_pause)
        stopButton = findViewById(R.id.btn_stop)
        seekBar = findViewById(R.id.seek_bar)
        statusText = findViewById(R.id.text_status)
        progressText = findViewById(R.id.text_progress)
    }
    
    private fun initMediaPlayer() {
        mediaPlayer = MediaPlayer()
        try {
            // 使用系统自带的音频示例文件，或者您可以使用网络音频链接
            mediaPlayer?.setDataSource("https://www.soundhelix.com/examples/mp3/SoundHelix-Song-1.mp3")
            mediaPlayer?.prepareAsync()
            statusText.text = "状态: 正在准备音频..."
            
            mediaPlayer?.setOnPreparedListener {
                statusText.text = "状态: 准备完成"
                seekBar.max = it.duration
                updateProgressText(0, it.duration)
            }
            
            mediaPlayer?.setOnCompletionListener {
                statusText.text = "状态: 播放完成"
                playButton.isEnabled = true
                pauseButton.isEnabled = false
                stopButton.isEnabled = false
            }
            
        } catch (e: IOException) {
            e.printStackTrace()
            Toast.makeText(this, "无法加载音频文件", Toast.LENGTH_SHORT).show()
        }
    }
    
    private fun setupListeners() {
        playButton.setOnClickListener {
            playAudio()
        }
        
        pauseButton.setOnClickListener {
            pauseAudio()
        }
        
        stopButton.setOnClickListener {
            stopAudio()
        }
        
        seekBar.setOnSeekBarChangeListener(object : SeekBar.OnSeekBarChangeListener {
            override fun onProgressChanged(seekBar: SeekBar?, progress: Int, fromUser: Boolean) {
                if (fromUser) {
                    mediaPlayer?.seekTo(progress)
                }
            }
            
            override fun onStartTrackingTouch(seekBar: SeekBar?) {}
            
            override fun onStopTrackingTouch(seekBar: SeekBar?) {}
        })
        
        // 启动进度更新线程
        Thread {
            while (!Thread.currentThread().isInterrupted) {
                try {
                    Thread.sleep(1000)
                    runOnUiThread {
                        updateProgress()
                    }
                } catch (e: InterruptedException) {
                    break
                }
            }
        }.start()
    }
    
    private fun playAudio() {
        mediaPlayer?.let {
            if (!it.isPlaying) {
                it.start()
                statusText.text = "状态: 正在播放"
                playButton.isEnabled = false
                pauseButton.isEnabled = true
                stopButton.isEnabled = true
            }
        }
    }
    
    private fun pauseAudio() {
        mediaPlayer?.let {
            if (it.isPlaying) {
                it.pause()
                statusText.text = "状态: 已暂停"
                playButton.isEnabled = true
                pauseButton.isEnabled = false
            }
        }
    }
    
    private fun stopAudio() {
        mediaPlayer?.let {
            if (it.isPlaying) {
                it.stop()
                it.prepareAsync()
                statusText.text = "状态: 已停止"
                playButton.isEnabled = true
                pauseButton.isEnabled = false
                stopButton.isEnabled = false
                seekBar.progress = 0
            }
        }
    }
    
    private fun updateProgress() {
        mediaPlayer?.let {
            if (it.isPlaying) {
                val currentPosition = it.currentPosition
                val duration = it.duration
                seekBar.progress = currentPosition
                updateProgressText(currentPosition, duration)
            }
        }
    }
    
    private fun updateProgressText(currentPosition: Int, duration: Int) {
        val currentMinutes = currentPosition / 1000 / 60
        val currentSeconds = currentPosition / 1000 % 60
        val durationMinutes = duration / 1000 / 60
        val durationSeconds = duration / 1000 % 60
        
        progressText.text = String.format(
            "%02d:%02d / %02d:%02d",
            currentMinutes, currentSeconds,
            durationMinutes, durationSeconds
        )
    }
    
    override fun onDestroy() {
        super.onDestroy()
        mediaPlayer?.release()
        mediaPlayer = null
    }
}